/**
 * @Title: SysAuthorizingRealm.java
 * @Package com.yly.module.sys.security
 * @Description: TODO
 * @author zz
 * @date 2014-3-2 上午11:04:10
 * @version V1.0
 */
package com.yly.module.sys.security.realm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.yly.utils.StrUtil;

/**
 * @ClassName: SysAuthorizingRealm
 * @Description: TODO
 * @author zz
 * @date 2014-3-2 上午11:04:10
 */
@Component
public class SysAuthorizingRealm extends AuthorizingRealm {

	protected static Log loger = LogFactory.getLog(SysAuthorizingRealm.class);
	
	// 用于获取用户信息及用户权限信息的业务接口
	@Resource
	private ISysAuthorizingRealmDao sysAuthorizingRealmDaoImpl;

	// 获取认证信息
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		// 通过表单接收的用户名
		String username = token.getUsername();
		
		if (!StrUtil.nil(username)) {
			Map param = new HashMap();
			param.put("user_code", username);
			Map userMap = sysAuthorizingRealmDaoImpl.getUserInfo(param);
			if (userMap != null && !userMap.isEmpty()) {
				return new SimpleAuthenticationInfo(userMap.get("user_code"),
						userMap.get("password"), getName());
			}
		}

		return null;
	}

	// 获取授权信息
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator()
				.next();

		if (!StrUtil.nil(username)) {
			Map param = new HashMap();
			param.put("user_code", username);
			// 查询用户授权信息
			Map userMap = sysAuthorizingRealmDaoImpl.getUserRoleInfo(param);
			if (!userMap.isEmpty()) {
				SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
				List<String> roleList = (List) userMap.get("role");
				//info.addRoles(roleList);
				info.addStringPermissions(roleList);
				return info;
			}
		}

		return null;
	}

	public ISysAuthorizingRealmDao getSysAuthorizingRealmDaoImpl() {
		return sysAuthorizingRealmDaoImpl;
	}

	public void setSysAuthorizingRealmDaoImpl(
			ISysAuthorizingRealmDao sysAuthorizingRealmDaoImpl) {
		this.sysAuthorizingRealmDaoImpl = sysAuthorizingRealmDaoImpl;
	}

	
}
